package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.security.service.TokenService;
import com.jcfk.common.web.domain.LoginInfo;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.dao.RefRolePermissionMappingDao;
import com.jcfk.system.dao.SysPermissionDao;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.dto.SysPermissionDTO;
import com.jcfk.system.domain.po.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

@Service
public class LoginUserPowerService {

    @Autowired
    private RefRolePermissionMappingDao refRolePermissionMappingDao;

    @Autowired
    private SysPermissionDao sysPermissionDao;

    @Autowired
    private TokenService tokenService;

    public List<SysPermissionDTO> getUserPimss(String applicationType, String parentMenuId) {

        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();

        List<SysPermissionDTO> tree = new ArrayList<>();

        List<SysPermissionDTO> permissionDTOS = new ArrayList<>();
        // 用户信息为空或者普通用户 直接返回
        if (loginInfo == null) return tree;

        // 超级管理员
        if ("superadmin".equals(loginInfo.getUserType())) {
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();

            queryWrapper.eq("deleted", 0)
                    .eq(!StringUtils.isEmpty(applicationType), "application_type", applicationType)
                    .ne("permission_type", 2).orderByAsc("sort");
            queryWrapper.select("id,parent_id,permission_code,permission_name,permission_type,url,icon,sort,application_type,enabled,page_target,show_type");
            List<SysPermission> permissions = sysPermissionDao.selectList(queryWrapper);
            permissionDTOS = convertList(permissions, SysPermissionDTO.class);
        } else {
            permissionDTOS = refRolePermissionMappingDao.queryPimss(LoginUserInfoUtils.getUserId(), applicationType, parentMenuId);
        }


        Map<String, List<SysPermissionDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (SysPermissionDTO node : permissionDTOS) {
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        if(StrUtil.isEmpty(parentMenuId)){
            parentMenuId="0";
            buildTree(tree, parentChildMap, "0");
        }
        else
        {
            buildTree(tree, parentChildMap, parentMenuId);
        }

        return tree;
    }

    public String[] queryPimssCode(String applicationType) {

        List<SysPermissionDTO> codes = new ArrayList<>();
        LoginInfo loginInfo = tokenService.getLoginInfo();

        // 用户信息为空或者普通用户 直接返回
        if (loginInfo == null) return new String[0];

        // 超级管理员
        if ("superadmin".equals(loginInfo.getUserType())) {
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0).eq(!StringUtils.isEmpty(applicationType), "application_type", applicationType).eq("permission_type", 2).select("id,parent_id,permission_code,permission_name,permission_type,url,icon,sort,application_type,enabled");
            List<SysPermission> permissions = sysPermissionDao.selectList(queryWrapper);
            codes = convertList(permissions, SysPermissionDTO.class);
        }else {
            codes = refRolePermissionMappingDao.queryPimssCode(LoginUserInfoUtils.getUserId(), applicationType);
        }


        // 返回数组
        List<String> code = codes.stream().map(SysPermissionDTO::getPermissionCode).collect(Collectors.toList());
        String[] retcode = code.toArray(new String[0]);

        return retcode;
    }


    /**
     * 根据条件获取用户分页列表
     *
     * @param tree           树
     * @param parentChildMap 节点集合
     * @param parentId       父id
     */
    private static void buildTree(List<SysPermissionDTO> tree, Map<String, List<SysPermissionDTO>> parentChildMap, String parentId) {
        List<SysPermissionDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (SysPermissionDTO child : children) {
                List<SysPermissionDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getChildren(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 权限过滤
     * @param codes
     */
    public List<SysPermissionDTO> filterUserPermissionList(List<String> codes){
        List<SysPermissionDTO> list =null;

        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();
        if ("superadmin".equals(loginInfo.getUserType())) {
            list = refRolePermissionMappingDao.filterPermissionList(LoginUserInfoUtils.getUserId(), codes);
        }
        else
        {
            list = refRolePermissionMappingDao.filterAdminPermissionList(LoginUserInfoUtils.getUserId(), codes);
        }

        return list;
    }
}
